from utils.assertutil import AssertUtil
from utils.yamlutil import YamlUtil
from utils.logutil import getlog


class ExtractUtil:
    def __init__(self):
        self.jsonpath_value1 = AssertUtil()
        self.yamlutil = YamlUtil()

    def extractUtil(self, res, extract):
        if extract :
            for key, values in extract.items():
                try:
                    result = self.jsonpath_value1.jsonpath_value(res, values)
                    self.yamlutil.write_yaml({key: result})
                except Exception as e:
                    getlog.error(f"写入到extract.yaml中失败，失败的情况是：{e}")
        else:
            return

    def get_extract_value(self, key):
        try:
            result = YamlUtil().read_yaml_noparams()
            return result[key]
        except Exception as e:
            getlog.error(f"通过{key}获取对应的值失败，失败的情况是：{e}")

    def new_url(self, url):
        if "${" in url and "}" in url:
            return self.process_func(url)
        else:
            return url

    def process_func(self, data):
        # /orders/${get_extract_value(order_id)}/
        for i in range(data.count("${")):
            if "${" in data and "}" in data:
                start_index = data.index("${")
                end_index = data.index("}")
                # 获取函数方法名
                func_full_name = data[start_index: end_index + 1]
                # 获取方法名
                func_name = data[start_index + 2: data.index("(")]
                # 获取参数
                func_params = data[data.index("(") + 1:data.index(")")]

                # 进行 getattr 处理
                extract_data = getattr(self, func_name, None)
                if extract_data is not None:
                    # 根据参数的数量进行处理
                    func_params = func_params.split(',') if func_params else []

                    # 处理参数中有数字的情况
                    func_params = [int(params) if params.isdigit() else params for params in func_params]

                    extract_data = extract_data(*func_params)
                data = data.replace(func_full_name, str(extract_data))
        return data
